package cc.owoo.godpen.analysis.json;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 当值为数组时，能够进行的操作
 * Created by nimensei
 * 2022-05-16 上午 10:42
 **/
public final class JsonArray extends Json {
    private Object data;// 数组数据
    private int length;// 数组长度

    JsonArray(Object data) {
        this.data = data;
        length = Array.getLength(data);
    }

    @Override
    public Object getData() {
        return data;
    }

    @Override
    public boolean setData(Object data) {
        if (!data.getClass().isArray())
            return false;
        this.data = data;
        length = Array.getLength(data);
        return true;
    }

    @Override
    boolean setValue(String key, Object value) {
        return false;
    }

    @Override
    boolean setValue(int index, Object value) {
        if (index < 0 || index >= length)
            return false;
        try {
            Array.set(data, index, value);
        } catch (Exception ignored) {
            return false;
        }
        return true;
    }

    @Override
    Object getValue(String key) {
        return null;
    }

    @Override
    Object getValue(int index) {
        if (index < 0 || index >= length)
            return null;
        try {
            return Array.get(data, index);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Object removeValue(String key) {
        return null;
    }

    @Override
    public Object removeValue(int index) {
        return null;
    }

    @Override
    Boolean getBooleanValue() {
        return null;
    }

    @Override
    Number getNumberValue() {
        return null;
    }

    @Override
    CharSequence getCharSequenceValue() {
        return null;
    }

    @Override
    public HashMap<String, Object> getHashMap() {
        return null;
    }

    @Override
    public ArrayList<Object> getArrayList() {
        ArrayList<Object> list = new ArrayList<>(length);
        for (int i = 0; i < length; i++)
            try {
                list.add(Array.get(data, i));
            } catch (Exception e) {
                return null;
            }
        return list;
    }
}
